<template>
  <div class="profile-container">
    <div class="profile-sidebar">
      <el-menu :default-active="activeTab" class="profile-menu" @select="handleSelect">
        <el-menu-item index="info">
          <el-icon>
            <User />
          </el-icon>
          <span>我的信息</span>
        </el-menu-item>
        <el-menu-item index="coupons">
          <el-icon>
            <Ticket />
          </el-icon>
          <span>我的优惠券</span>
        </el-menu-item>
        <el-menu-item index="points">
          <el-icon>
            <Coin />
          </el-icon>
          <span>我的积分</span>
        </el-menu-item>
        <el-menu-item index="orders">
          <el-icon>
            <Document />
          </el-icon>
          <span>我的订单</span>
        </el-menu-item>
        <el-menu-item index="addresses">
          <el-icon>
            <Location />
          </el-icon>
          <span>收货地址</span>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="profile-content">
      <!-- 我的信息 -->
      <user-info 
        v-if="activeTab === 'info'" 
        :user-info="userInfo"
        :user-info-form="userInfoForm"
        :default-avatar="defaultAvatar"
        @update-profile="updateProfile"
        @avatar-success="handleAvatarSuccess"
        @before-upload="beforeAvatarUpload"
      />

      <!-- 我的优惠券 -->
      <my-coupons 
        v-if="activeTab === 'coupons'" 
        :status="couponStatus"
      />

      <!-- 我的积分 -->
      <my-points 
        v-if="activeTab === 'points'"
      />

      <!-- 我的订单 -->
      <my-orders 
        v-if="activeTab === 'orders'"
        :status="orderStatus"
        @status-change="handleOrderStatusChange"
      />

      <!-- 收货地址 -->
      <my-addresses 
        v-if="activeTab === 'addresses'"
        :addresses="addresses"
        @fetch-addresses="fetchAddresses"
        @edit="editAddress"
        @delete="deleteAddress"
        @save="saveAddress"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Ticket,
  Coin,
  Document,
  Location
} from '@element-plus/icons-vue'
import { useProfileStore } from '@/store/profile'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import UserInfo from './profile/UserInfo.vue'
import MyCoupons from './profile/MyCoupons.vue'
import MyPoints from './profile/MyPoints.vue'
import MyOrders from './profile/MyOrders.vue'
import MyAddresses from './profile/MyAddresses.vue'
import {
  getAddresses,
  saveAddress as apiSaveAddress,
  updateAddress as apiUpdateAddress,
  deleteAddress as apiDeleteAddress,
  getProvinces,
  getCities,
  getdistricts,
  updateUserInfo
} from '@/api/profile'
import type { User as UserType, UserInfoType, UserAddressType } from '@/type/user'

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 当前激活的标签页
const activeTab = ref('info')

const profileStore = useProfileStore()
const route = useRoute()

// 用户信息相关
const userInfo = computed<UserType>(() => {
  return profileStore.user
})

// 用户信息表单
const userInfoForm = ref({
  avatar: '',
  nickname: '',
  phone: '',
  email: '',
  username: '',
  birthday: '',
  gender: 1,
  address: '',
  description: ''
})

// 监听用户信息变化，更新表单
watch(() => profileStore.user, (newUser) => {
  if (newUser && newUser.id) {
    userInfoForm.value = {
      avatar: newUser.avatarUrl || '',
      nickname: newUser.nickname || newUser.username,
      phone: newUser.phone || '',
      email: newUser.email || '',
      username: newUser.username || '',
      birthday: newUser.birthday || '',
      gender: newUser.gender !== undefined ? newUser.gender : 1,
      address: newUser.address || '',
      description: newUser.description || ''
    }
  }
}, { immediate: true })

// 地址相关
const addresses = ref<any[]>([])

// 优惠券状态
const couponStatus = ref('1')

// 订单状态
const orderStatus = ref('0')

// 切换标签页
const handleSelect = (index: string) => {
  activeTab.value = index
  switch (index) {
    case 'info':
      // 用户信息已通过store自动获取，不需要额外请求
      break
    case 'coupons':
      // 不需要在这里获取数据，由MyCoupons组件自己管理
      break
    case 'points':
      // 不需要在这里获取数据，由MyPoints组件自己管理
      break
    case 'orders':
      // 不需要在这里获取数据，由MyOrders组件自己管理
      break
    case 'addresses':
      fetchAddresses()
      break
  }
}

// 订单状态变更处理
const handleOrderStatusChange = (status: string) => {
  orderStatus.value = status
}

// 更新用户信息
const updateProfile = async (userInfoData: UserInfoType) => {
  try {
    await updateUserInfo(userInfoData)
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const res = await getAddresses()
    addresses.value = res.data.data

    // 通知子组件更新数据
    const event = new CustomEvent('addresses-updated', { detail: res.data.data });
    window.dispatchEvent(event);
  } catch (error) {
    ElMessage.error('获取地址列表失败')
  }
}

// 编辑地址
const editAddress = (address: any) => {
  // 触发子组件的编辑事件
  const event = new CustomEvent('edit-address', { detail: address });
  window.dispatchEvent(event);
}

// 保存地址
const saveAddress = async (addressData: UserAddressType, isEdit: boolean) => {
  try {
    if (isEdit) {
      await apiUpdateAddress(addressData)
      ElMessage.success('更新成功')
    } else {
      await apiSaveAddress(addressData)
      ElMessage.success('添加成功')
    }
    fetchAddresses()
  } catch (error) {
    ElMessage.error(isEdit ? '更新失败' : '添加失败')
  }
}

// 删除地址
const deleteAddress = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await apiDeleteAddress(id)
    ElMessage.success('删除成功')
    fetchAddresses()
  } catch (error: any) {
    if (error !== 'cancel' && error !== undefined) {
      ElMessage.error('删除失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 头像上传相关
const handleAvatarSuccess = (res: any) => {
  // 更新用户头像
  userInfoForm.value.avatar = res.data.url
  ElMessage.success('头像上传成功')
}

const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 验证token有效性
const validateToken = async () => {
  if (!profileStore.isLoggedIn) {
    return false;
  }

  try {
    await profileStore.validateToken();
    return true;
  } catch (error) {
    return false;
  }
};

onMounted(async () => {
  // 验证token有效性
  const isValid = await validateToken();
  if (!isValid) {
    // 如果token无效，重定向到首页并显示登录对话框
    window.location.href = '/#/'; // 使用这种方式强制刷新路由
    setTimeout(() => {
      const event = new CustomEvent('showLoginDialog');
      window.dispatchEvent(event);
    }, 100);
    return;
  }

  // 用户信息在登录时已经获取并存储在store中，无需再次请求
  // 根据默认激活的标签页加载对应数据
  if (activeTab.value !== 'info') {
    handleSelect(activeTab.value)
  }
})
</script>

<style scoped>
.profile-container {
  display: flex;
  min-height: calc(100vh - 60px);
}

.profile-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.profile-menu {
  border-right: none;
}

.profile-content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
}

@media (max-width: 768px) {
  .profile-container {
    flex-direction: column;
  }
  
  .profile-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e6e6e6;
  }
}
</style>